package com.zxw.user.exception;

import com.zxw.common.core.base.enums.ResponseEnum;
import com.zxw.common.core.base.res.BaseRes;
import com.zxw.common.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.lang.reflect.UndeclaredThrowableException;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class UserExceptionHandler {

    private static final long serialVersionUID = -7665005331526034437L;

    @ExceptionHandler({AppException.class})
    public BaseRes appException(AppException ex) {
        ex.printStackTrace();
        if (null == ex.getAdditionalMsg()) {
            return BaseRes.err(ex.getCode(), ex.getMsg());
        } else {
            return BaseRes.err(ex.getCode(), ex.getMsg() + ex.getAdditionalMsg());
        }
    }


    @ExceptionHandler({UndeclaredThrowableException.class})
    public BaseRes otherException(UndeclaredThrowableException ex) {
        ex.printStackTrace();
        return BaseRes.err(ResponseEnum.NORMAL_ERROR.getCode(), ex.getUndeclaredThrowable().getMessage());
    }

    /**
     * 自定义参数验证异常拦截
     *
     * @param ex
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public BaseRes validationException(MethodArgumentNotValidException ex) {
        return BaseRes.err(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    //其他错误
    @ExceptionHandler({Exception.class})
    public BaseRes otherException(Exception ex) {
        ex.printStackTrace();
        if (ObjectUtils.isEmpty(ex.getMessage())) {
            return BaseRes.err(ResponseEnum.NORMAL_ERROR.getCode(), ResponseEnum.NORMAL_ERROR.getMsg());
        } else {
            return BaseRes.err(ResponseEnum.NORMAL_ERROR.getCode(), ex.getMessage());
        }
    }

}
